<script setup lang="ts">
import type { PerBusinessPositionExperienceApi } from '#/api/per/businessPositionExperience';

import { ref, watch } from 'vue';

import { message } from 'ant-design-vue';

import { getPositionExperienceBusiId } from '#/api/per/businessPositionExperience';

import PositionExperienceDetail from './positionExperienceDetail.vue';
import PositionExperienceEdit from './positionExperienceEdit.vue';

const props = defineProps<{
  busiId?: number | string;
  editFlag?: boolean;
}>();

const formData =
  ref<PerBusinessPositionExperienceApi.BusinessPositionExperience>();
const editRef = ref<any>();
const mode = ref<'edit' | 'view'>('view');

async function getFormData() {
  const data = await editRef.value?.getFormData();
  return data;
}

// 暴露给父组件
defineExpose({ getFormData });

watch(
  () => props.busiId,
  async (newVal) => {
    if (!newVal) return;
    await loadData(newVal);
  },
  { immediate: true },
);

watch(
  () => props.editFlag,
  (flag) => (mode.value = flag ? 'edit' : 'view'),
  { immediate: true },
);

async function loadData(id: number | string) {
  try {
    formData.value = await getPositionExperienceBusiId({ busiId: id });
  } catch (error) {
    console.error(error);
    message.error('加载详情失败');
  }
}
</script>

<template>
  <PositionExperienceDetail v-if="mode === 'view'" :data="formData" />
  <PositionExperienceEdit v-else ref="editRef" :data="formData" />
</template>
